<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="username" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="minage" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="mingender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="fn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr v-if="list.length">
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="fn1(item.id)">删除</button>
            <button @click="fn2(item.id, index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          id: 1,
          uname: 'dddd',
          age: 18,
          gender: '男',
        },
      ],
      username: '',
      minage: '',
      mingender: '',
      fage: true,
      iidd: '',
      dindex: '',
    }
  },
  methods: {
    fn() {
      if (this.iidd) {
        this.list.forEach((item) => {
          if (item.id === this.iidd) {
            const obj = {
              id: this.list[this.dindex].id,
              uname: (this.list[this.dindex].uname = this.username),
              age: (this.list[this.dindex].age = this.minage),
              gender: (this.list[this.dindex].gender = this.mingender),
            }
            this.list.splice(this.dindex, 1, obj)
            this.iidd = ''
                this.username = ''
          this.minage = ''
          this.mingender = ''
          }
         
        })
      } else {
        console.log(1)
        
        if ((this.username && this.minage && this.mingender)) {
          const obj = {
            id: this.list.length + 1,
            uname: this.username,
            age: this.minage,
            gender: this.mingender,
          }
          this.list = [...this.list, obj]
          this.username = ''
          this.minage = ''
          this.mingender = ''
        } else {
          alert('请输入有效姓名年龄性别')
        }
       
      }
    },
    fn1(a) {
      this.list = this.list.filter((item) => {
        return item.id !== a
      })
    },
    fn2(a, b) {
      this.list.forEach((item) => {
        this.iidd = a
        this.dindex = b
        if (item.id === a) {
          (this.username = item.uname),
            (this.minage = item.age),
            (this.mingender = item.gender)
        }
      })
    },
  },
}
</script>
